﻿//
// Created by 17616 on 2021/5/11.
//
#include <vector>
#include <string>
#include <exception>
#include <iostream>
#include "public.h"
#include <opencv2/opencv.hpp>
#include <thread>
#include "LockFreeLinkedQueue.h"
LockFreeLinkedQueue<int> lf_queue;
std::vector<int> CompressionPara = {
        cv::IMWRITE_PNG_COMPRESSION,
        5//参数越大，压缩比例越高
};


int m_main(const std::vector<std::string> &args) {
    std::cout << "输入压缩等级(1-9)(默认5)" << std::endl;
    int num;
    std::cin >> num;
    if (1 <= num && num <= 9) {
        CompressionPara[1] = num;
    }
    std::cout << CompressionPara[1] << std::endl;
    for (int i = 0; i < args.size(); ++i) {
        lf_queue.push(i);
    }
    printf("Hardware concurrency=%d\r\n", std::thread::hardware_concurrency());
    thread_pool tp(0, std::thread::hardware_concurrency());
    tp.post([&args](int s, int e) {
        cv::Mat mat;
        int i;
        while (lf_queue.tryPop(i)) {
            mat = cv::imread(args[i], cv::IMREAD_UNCHANGED);
            printf("压缩%s ......\r\n", args[i].c_str());
            if (args[i].find(".png") != std::string::npos) {
                std::string buf = args[i];
                cv::imwrite(replace_str(buf, ".", "") + ".png", mat, CompressionPara);
            } else {
                cv::imwrite(GetFilePathWithoutType(args[i]) + ".png", mat, CompressionPara);
            }
        }
    });
    tp.join();

    std::cout << "转换完成，是否删除源文件?y or n(默认n):";
    char answer = 'n';
    std::cin >> answer;
    std::cout << answer << std::endl;
    if (answer == 'y' || answer == 'Y') {
        for (const auto &i:args) {
            remove(i.c_str());
        }
    }

    return 0;
}


int main(int argn, const char **argv) {
    if (argn == 1) {
        printf("Bmp文件转换png程序\r\n");
        std::system("pause");
        return 0;
    }
    std::vector<std::string> args;
    if (strcmp(argv[1], "--test") == 0) {
        args.push_back("C:\\Users\\17616\\Pictures\\Snipaste_2021-05-15_13-43-20.png.png");
    } else {
        for (int i = 1; i < argn; ++i) {
            args.emplace_back(argv[i]);
        }
    }
    return m_main(args);
}